package im.starchat.chat.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import im.starchat.chat.R;
import im.starchat.chat.XLApplication;
import im.starchat.chat.activity.profile.ContributionActivity;
import im.starchat.chat.adapter.SmartFragmentStatePagerAdapter;
import im.starchat.chat.adapter.TabTypeTwoAdapter;
import im.starchat.chat.dialog.ShareProfileDialogFragment;
import im.starchat.chat.fragment.StarLiveFragment;
import im.starchat.chat.fragment.StarPreviewFragment;
import im.starchat.chat.rest.RestClient;
import im.starchat.chat.rest.model.ContributionBean;
import im.starchat.chat.rest.model.UserBean;
import im.starchat.chat.rest.model.api.NullResponse;
import im.starchat.chat.view.CircularImageButton;
import im.starchat.chat.view.HorizontalListView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;


/**
 * 明星主页
 */
public class StarActivity extends BaseActivity implements View.OnClickListener{

    public static final String USER_ID = "user_id";

//    @InjectView(R.id.scroll_view)
//    PullToZoomScrollViewEx scrollView;
    @InjectView(R.id.back)
    ImageView mBackBtn;
    @InjectView(R.id.share)
    ImageView mShareBtn;

    private TabTypeTwoAdapter mClassTabAdapter;

    StarLiveFragment mLiveFragment;
    StarPreviewFragment mPreviewragment;
    LivePagerAdapter mLiveAdapter;
    List<Fragment> liveFragmentList;
    private ArrayList<String> mTabs = new ArrayList<>();
    StarPagerOnPageChangeListener mStarPagerOnPageChangeListener;
    private int mCurrentTab = 0;

    private String mUserId;

    @InjectView(R.id.profile_user_name)
    TextView mUserName;
    @InjectView(R.id.profile_user_sex)
    TextView mUserSex;
    @InjectView(R.id.profile_user_detail)
    TextView mUserDetail;
    @InjectView(R.id.fan_count)
    TextView mFansCount;
    @InjectView(R.id.iv_zoom)
    ImageView mUserHeaderCover;
    @InjectView(R.id.attention)
    TextView mAttention;
    @InjectView(R.id.cancel_attention)
    TextView mCancelAttention;
    @InjectView(R.id.content_viewpager)
    ViewPager mLiveViewPager;
    @InjectView(R.id.horizon_listview)
    HorizontalListView mHorizontalTabListView;
//    @InjectView(R.id.tv_register)
//    TextView mContributionTextview;
    @InjectView(R.id.show_more)
    ImageView mShowMore;
    @InjectView(R.id.star_ider)
    ImageView mStarIder;

    @InjectView(R.id.contribution_user_layout)
    LinearLayout mContributionUserLayout;

    private UserBean mUserBean;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_star);
        ButterKnife.inject(this);

        Intent intent = getIntent();
        if(intent != null){
            mUserId = intent.getStringExtra(USER_ID);
        }
        if(!TextUtils.isEmpty(mUserId)){
            liveFragmentList = new ArrayList<>();
            mLiveFragment = StarLiveFragment.newInstance(mUserId);
            liveFragmentList.add(mLiveFragment);
            mPreviewragment = StarPreviewFragment.newInstance(mUserId);
            liveFragmentList.add(mPreviewragment);
        }

        initScrollView();

//        LinearLayout.LayoutParams localObject = new LinearLayout.LayoutParams(XLApplication.sScreenWidth, (int) (9.0F * (XLApplication.sScreenWidth / 16.0F)));
//        scrollView.setHeaderLayoutParams(localObject);

        getUserInfo(mUserId);
        getContributionList(mUserId);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.show_more:
                Intent contributionIntent = new Intent(StarActivity.this, ContributionActivity.class);
                contributionIntent.putExtra(ContributionActivity.FLAG_USER_ID, mUserId);
                startActivity(contributionIntent);
                break;
        }
    }

    public class LivePagerAdapter extends SmartFragmentStatePagerAdapter {
        List<Fragment> fragmentList;

        public LivePagerAdapter(android.support.v4.app.FragmentManager fragmentManager, List<Fragment> fragments) {
            super(fragmentManager);
            this.fragmentList = fragments;
        }

        @Override
        public Fragment getItem(int position) {

            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            if(fragmentList != null){
                return fragmentList.size();
            }
            return 0;
        }
    }

    public class StarPagerOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
//            favTypeHost.check(position == 0 ? R.id.fav_topic : R.id.fav_comic);
            //TODO 主界面接口回调
            mClassTabAdapter.setSelectIndex(position);
            mClassTabAdapter.notifyDataSetChanged();
            mCurrentTab = position;

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }


    //获取明星资料
    private void getUserInfo(String userId){
        if(!TextUtils.isEmpty(userId))
        XLApplication.getInstance().getRestClient().getUserInfo(userId, new Callback<UserBean>() {
            @Override
            public void success(UserBean userBean, Response response) {
//                UserUtils.setUserInstance(userBean);
//                PreferencesStorageUtil.setUserBean(StarActivity.this, GsonUtil.toJson(userBean));
                mUserBean = userBean;
                refreshAccount(userBean);
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    private void refreshAccount(UserBean userBean){
        if(userBean != null){
            mUserName.setText(userBean.getNickname());
            mUserSex.setText(userBean.getGender_text());
            if(!TextUtils.isEmpty(userBean.getDescription())){
                mUserDetail.setText(userBean.getDescription());
            }
//                mZhiboCount.setText("0");
//                mFansCount.setText("0");
            mFansCount.setText("粉丝" + userBean.getFollowers_count() + "");
            if(userBean.is_following()){
                mAttention.setVisibility(View.GONE);
                mCancelAttention.setVisibility(View.VISIBLE);
            }else{
                mAttention.setVisibility(View.VISIBLE);
                mCancelAttention.setVisibility(View.GONE);
            }
            if(!TextUtils.isEmpty(userBean.getAvatar())){

                Picasso.with(StarActivity.this).load(userBean.getAvatar())
                        .placeholder(R.drawable.ic_img_profile_bg)
                        .into(mUserHeaderCover);
            }
            if(userBean.getUser_type().equals("star")){
                mStarIder.setVisibility(View.VISIBLE);
            }else{
                mStarIder.setVisibility(View.GONE);
            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult( requestCode, resultCode, data);
    }

    private void initScrollView(){

        mBackBtn.setOnClickListener(this);
        mShowMore.setOnClickListener(this);
//        mContributionTextview.setOnClickListener(this);
        final ShareProfileDialogFragment shareAppDialogFragment = ShareProfileDialogFragment.newInstance();
        mShareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareAppDialogFragment.show(getSupportFragmentManager().beginTransaction(), "share_profile");
            }
        });


        mAttention.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                following(mUserId);
            }
        });
        mCancelAttention.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancelFollowing(mUserId);
            }
        });

//        mHorizontalTabListView = (HorizontalListView) contentView.findViewById(R.id.horizon_listview);
//        mLiveViewPager = (ViewPager) contentView.findViewById(R.id.content_viewpager);
        mLiveAdapter = new LivePagerAdapter(getSupportFragmentManager(), liveFragmentList);
        mLiveViewPager.setAdapter(mLiveAdapter);

        mStarPagerOnPageChangeListener = new StarPagerOnPageChangeListener();
        mLiveViewPager.setOnPageChangeListener(mStarPagerOnPageChangeListener);
        mLiveViewPager.setCurrentItem(0);

        mTabs.add("直播");
        mTabs.add("活动预告");
        mClassTabAdapter = new TabTypeTwoAdapter(
                StarActivity.this,mTabs);
        mHorizontalTabListView
                .setAdapter(mClassTabAdapter);
        mHorizontalTabListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                mClassTabAdapter.setSelectIndex(arg2);
                mClassTabAdapter.notifyDataSetChanged();
                mLiveViewPager.setCurrentItem(arg2);
                mCurrentTab = arg2;
            }
        });

    }


    private void following(String id){
        XLApplication.getInstance().getRestClient().following(id, "", new Callback<NullResponse>() {
            @Override
            public void success(NullResponse nullResponse, Response response) {
                Toast.makeText(StarActivity.this, "关注成功", Toast.LENGTH_SHORT).show();
                if(mUserBean != null){
                    mUserBean.setFollowers_count(mUserBean.getFollowers_count() + 1);
                    mUserBean.setIs_following(true);
                    refreshAccount(mUserBean);
                }
            }

            @Override
            public void failure(RetrofitError error) {
            }
        });
    }

    private void cancelFollowing(String id){
        XLApplication.getInstance().getRestClient().delFollowing(id, new Callback<NullResponse>() {
            @Override
            public void success(NullResponse nullResponse, Response response) {
                Toast.makeText(StarActivity.this, "取消关注成功", Toast.LENGTH_SHORT).show();
                if (mUserBean != null) {
                    if (mUserBean.getFollowers_count() > 0) {
                        mUserBean.setFollowers_count(mUserBean.getFollowers_count() - 1);
                        mUserBean.setIs_following(false);
                        refreshAccount(mUserBean);
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    private void getContributionList(String userId){
        XLApplication.getInstance().getRestClient().getContributions(userId, 0, RestClient.DEFAULT_PREPAGE, new Callback<ContributionBean[]>() {
            @Override
            public void success(ContributionBean[] userBean, Response response) {

                int screenDp = (int) (XLApplication.sScreenWidth / XLApplication.sDensity);
                int maxNum = (screenDp / (44)) - 3;

                if (userBean != null) {
                    if (userBean.length > 0) {
                        mContributionUserLayout.removeAllViews();
                        for (int num = 0; num < userBean.length && num < maxNum; num++) {
                            View view = LayoutInflater.from(StarActivity.this).inflate(R.layout.view_contribution_user_layout, null, false);
                            CircularImageButton avator = (CircularImageButton) view.findViewById(R.id.avator);
                            if (userBean[num].getUser() != null && !TextUtils.isEmpty(userBean[num].getUser().getAvatar())) {
                                Picasso.with(StarActivity.this).load(userBean[num].getUser().getAvatar())
                                        .placeholder(R.drawable.channel_head01)
                                        .into(avator);
                            }
                            TextView contributionNum = (TextView) view.findViewById(R.id.contribution_num);
                            if (num < 3) {
                                contributionNum.setVisibility(View.VISIBLE);
                                contributionNum.setText((num + 1) + "");
                                if(num == 0){
                                    contributionNum.setBackgroundResource(R.drawable.bg_rounded_contribution_list1_bg);
                                }else if(num == 1){
                                    contributionNum.setBackgroundResource(R.drawable.bg_rounded_contribution_list2_bg);
                                }else if(num == 2){
                                    contributionNum.setBackgroundResource(R.drawable.bg_rounded_contribution_list3_bg);
                                }
                            } else {
                                contributionNum.setVisibility(View.GONE);
                            }
                            mContributionUserLayout.addView(view);
                        }
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
            }
        });
    }





}
